package com.controller;

import com.alibaba.fastjson.JSON;
import com.entity.ShopGoods;
import com.entity.ShopNews;
import com.entity.Userinfo;
import com.service.ShopNewsService;
import com.service.UserInfoService;
import com.util.CookieUtil;
import com.util.RedisUtil;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
public class UserInfoController {

    @Autowired
    private UserInfoService us;

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private HttpServletRequest request;

    @Autowired
    private ShopNewsService shopNewsService;


    @PostMapping("/dologin")
    public String dologin(Userinfo user, HttpServletRequest request, HttpServletResponse response) {
        System.out.println("-----nginx----");
        Userinfo userinfo = us.findByLoginNameAndPass(user);
        if (userinfo != null) {
            String token = "token" + userinfo.getId();
            String saveJSON = JSON.toJSONString(userinfo);
            String userKey = DigestUtils.md5Hex(token);
            redisUtil.set(userKey, saveJSON);
            CookieUtil.writeCookieToken(response, token);
            return "ok";
        } else {
            return "info";
        }
    }

    @RequestMapping("/login")
    public String login() {
        return "Login";
    }

    private String token() {
        return CookieUtil.readCookieToken(request);
    }

    @RequestMapping({"/", "/index"})
    public String index(Model model) {
        List<ShopGoods> list = null;
        String dbStr = redisUtil.get(token());
        if (dbStr != null) {
            list = JSON.parseArray(dbStr, ShopGoods.class);
        }
        model.addAttribute("cartList", list);
        List<ShopNews> newsPage = shopNewsService.getAllNews();
        model.addAttribute("newsList", newsPage);
        return "index";
    }

    @RequestMapping("/loginOut")
    public String loginOut(HttpServletRequest request, HttpServletResponse response) {
        CookieUtil.deleteToken(request, response);
        return "redirect:Login";

    }


}
